// pages/progress/index.js
const minLivingAllowanceAPI = require('../../../api/minLivingAllowance.js');
const authUtils = require('../../../utils/auth');
const { validateApplicationConsistency } = require('../../../utils/dataValidator');

Page({
  data: {
    keywords: '',
    currentStatus: 'all',
    currentStatusName: '全部状态',
    filteredApplications: [],
    filterOptions: [
      { id: 'all', name: '全部状态' },
      { id: 'pending', name: '待审核' },
      { id: 'approved', name: '已通过' },
      { id: 'rejected', name: '已驳回' }
    ],
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '用户信息加载中...',
    statusCounts: {},
    applications: [],
    loading: false,
    currentPage: 1,
    pageSize: 10,
    hasMore: true
  },

  // 显示全局加载
  showGlobalLoading(text = '用户信息加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad(options) {
    // 显示页面加载效果
    this.showGlobalLoading('用户信息加载中...')
    // 检查是否从申请页面跳转过来
    if (options.fromPage === 'apply') {
      this.setData({
        fromApplyPage: true
      });
    }
    this.loadApplications()
  },

  onShow() {
    this.loadApplications()
  },

  // 加载申请数据
  loadApplications: function() {
    var that = this;
    var currentUser = authUtils.getCurrentUser();
    if (!currentUser || !currentUser.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(function() {
        wx.navigateTo({
          url: '/pages/auth/login/index'
        });
      }, 1500);
      return;
    }

    that.setData({ loading: true });

    var params = {
      page: that.data.currentPage,
      limit: that.data.pageSize
    };

    // 如果当前状态不是全部，添加状态筛选
    if (that.data.currentStatus !== 'all') {
      params.status = that.data.currentStatus;
    }

    console.log('准备调用API，参数:', {
      userId: currentUser.userId,
      params: params
    });

    minLivingAllowanceAPI.getMyApplications(currentUser.userId, params)
      .then(function(response) {
        console.log('=== API响应数据 ===');
        console.log('完整响应:', JSON.stringify(response, null, 2));
        
        if (response && response.success) {
          console.log('API调用成功，原始申请数据:', JSON.stringify(response.data.applications, null, 2));
          
          var newApplications = that.formatApplications(response.data.applications);
          console.log('格式化后的申请数据:', JSON.stringify(newApplications, null, 2));
          
          // 如果是第一页，直接设置；否则追加
          var applications = that.data.currentPage === 1 ? newApplications : that.data.applications.concat(newApplications);
          
          that.setData({
            applications: applications,
            hasMore: response.data.pagination.page < response.data.pagination.pages,
            loading: false
          });
          
          console.log('页面数据已更新，applications数量:', applications.length);
          
          that.computeStatusCounts();
          // 确保筛选功能正常工作
          that.applyFilter();
          
          // 隐藏全局加载状态
          that.hideGlobalLoading();
        } else {
          console.error('API返回失败:', response);
          throw new Error(response.message || '获取数据失败');
        }
      })
      .catch(function(error) {
        console.error('加载申请数据失败:', error);
        that.setData({ 
          loading: false,
          applications: [],
          filteredApplications: []
        });
        
        // 隐藏全局加载状态
        that.hideGlobalLoading();
        
        // 显示错误信息
        let errorMessage = '网络错误，请重试';
        if (error.message) {
          errorMessage = error.message;
        } else if (error.type === 'network') {
          errorMessage = '网络连接失败，请检查网络设置';
        }
        
        wx.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
      });
  },

  // 格式化申请数据
  formatApplications: function(applications) {
    var that = this;
    return applications.map(function(app) {
      console.log('格式化申请数据 - 原始数据:', app);
      console.log('申请状态值:', app.status, '类型:', typeof app.status);
      console.log('apply_time字段值:', app.apply_time);
      console.log('process_time字段值:', app.process_time);
      console.log('review_time字段值:', app.review_time);
      
      // 使用数据验证工具确保状态和审核意见的一致性
      const validatedApp = validateApplicationConsistency({
        id: app.id,
        status: app.status,
        review_comment: app.review_comment,
        process_comment: app.process_comment
      });
      
      // 根据状态确定进度和步骤 - 简化为两个步骤
      var progress = 0;
      var currentStep = '';
      var nextStep = '';
      var statusText = '';

      // 确保状态值是字符串类型进行比较
      var status = String(app.status).toLowerCase();
      console.log('处理状态:', status);
      
      // 检查是否有statusText字段，如果有，优先使用它来判断状态
      var statusTextFromAPI = app.statusText || app.status_text;
      console.log('API返回的状态文本:', statusTextFromAPI);
      
      // 根据状态文本或状态值来确定进度
      if (statusTextFromAPI === '已通过' || statusTextFromAPI === '已完成' || status === 'approved' || status === 'completed') {
        // 第二步：管理员审核（已通过）
        progress = 100;
        currentStep = '管理员审核';
        nextStep = '';
        statusText = '已通过';
        // 统一设置为已通过状态
        app.status = 'approved';
        console.log('识别为已通过状态，进度设为100%');
      } else if (statusTextFromAPI === '已驳回' || status === 'rejected') {
        // 第二步：管理员审核（已驳回）
        progress = 100;
        currentStep = '管理员审核';
        nextStep = '重新申请';
        statusText = '已驳回';
        console.log('识别为已驳回状态，进度设为100%');
      } else if (statusTextFromAPI === '待审核' || status === 'pending') {
        // 第一步：用户提交申请（进行中）
        progress = 50;
        currentStep = '用户提交申请';
        nextStep = '管理员审核';
        statusText = statusTextFromAPI || '待审核';
        console.log('识别为进行中状态，进度设为50%');
      } else {
        // 默认状态：用户提交申请
        console.log('未知状态，使用默认处理:', status, '状态文本:', statusTextFromAPI);
        progress = 50;
        currentStep = '用户提交申请';
        nextStep = '管理员审核';
        statusText = '待审核';
      }
      
      console.log('进度计算结果 - 状态:', status, '进度:', progress, '当前步骤:', currentStep);
      console.log('原始状态值:', app.status, '转换后状态:', status);

      var formattedApp = {
        id: app.id.toString(),
        title: app.title || '最低生活保障申请',
        category: app.category || '民政社保',
        status: app.status,
        statusText: statusText,
        applyTime: that.formatDateTime(app.apply_time),
        updateTime: that.formatDateTime(app.process_time || app.review_time || app.apply_time),
        dept: app.dept || '民政办',
        progress: progress,
        currentStep: currentStep,
        nextStep: nextStep,
        description: app.description || '困难群众最低生活保障资格申请与复核',
        applicationNo: app.application_no,
        applicantName: app.applicant_name,
        familySize: app.family_size,
        monthlyIncome: app.monthly_income,
        incomeSource: app.income_source,
        rejectReason: app.status === 'rejected' ? (validatedApp.processComment || validatedApp.reviewComment || '申请材料不符合要求，请重新提交') : ''
      };
      
      console.log('格式化后的申请数据:', formattedApp);
      console.log('applyTime格式化结果:', formattedApp.applyTime);
      console.log('updateTime格式化结果:', formattedApp.updateTime);
      
      return formattedApp;
    })
  },

  // 格式化日期时间
  formatDateTime: function(dateTime) {
    console.log('formatDateTime 输入参数:', dateTime, '类型:', typeof dateTime);
    
    if (!dateTime) {
      console.log('dateTime为空，返回空字符串');
      return '';
    }
    
    try {
      var date = new Date(dateTime);
      console.log('转换后的Date对象:', date);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.log('无效的日期，返回空字符串');
        return '';
      }
      
      var year = date.getFullYear();
      var month = String(date.getMonth() + 1).padStart(2, '0');
      var day = String(date.getDate()).padStart(2, '0');
      var hours = String(date.getHours()).padStart(2, '0');
      var minutes = String(date.getMinutes()).padStart(2, '0');
      
      var result = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
      console.log('格式化结果:', result);
      return result;
    } catch (error) {
      console.error('格式化日期时间出错:', error);
      return '';
    }
  },

  // 计算各状态数量
  computeStatusCounts: function() {
    var counts = { all: this.data.applications.length };
    var that = this;
    this.data.applications.forEach(function(app) {
      counts[app.status] = (counts[app.status] || 0) + 1;
    });
    that.setData({ statusCounts: counts });
  },

  // 状态切换
  onTapStatus: function(e) {
    var id = e.currentTarget.dataset.id;
    var status = this.data.filterOptions.find(function(s) { return s.id === id; });
    this.setData({ 
      currentStatus: id, 
      currentStatusName: status ? status.name : '全部状态',
      keywords: ''
    });
    // 直接应用筛选，不重新加载数据
    this.applyFilter();
  },

  // 搜索
  onSearchConfirm: function(e) {
    this.setData({ keywords: (e.detail.value || '').trim() });
    this.applyFilter();
  },

  // 计算筛选结果
  applyFilter: function() {
    var applications = this.data.applications;
    var currentStatus = this.data.currentStatus;
    var keywords = this.data.keywords;
    var filtered = applications;

    console.log('开始筛选 - 当前状态:', currentStatus, '关键词:', keywords, '总数据量:', applications.length);

    // 按状态筛选
    if (currentStatus !== 'all') {
      filtered = filtered.filter(function(app) { 
        console.log('状态筛选 - 申请状态:', app.status, '目标状态:', currentStatus, '匹配:', app.status === currentStatus);
        return app.status === currentStatus; 
      });
    }

    // 按关键词搜索
    if (keywords) {
      filtered = filtered.filter(function(app) { 
        var titleMatch = app.title.indexOf(keywords) >= 0;
        var descMatch = app.description.indexOf(keywords) >= 0;
        var categoryMatch = app.category.indexOf(keywords) >= 0;
        var match = titleMatch || descMatch || categoryMatch;
        console.log('关键词筛选 - 标题:', titleMatch, '描述:', descMatch, '分类:', categoryMatch, '最终匹配:', match);
        return match;
      });
    }

    console.log('筛选完成 - 结果数量:', filtered.length);
    this.setData({ filteredApplications: filtered });
  },

  // 进入详情
  onTapItem: function(e) {
    console.log('点击事件触发:', e);
    var id = e.currentTarget.dataset.id;
    console.log('获取到的ID:', id);
    
    if (!id) {
      wx.showToast({
        title: '数据错误，请重试',
        icon: 'none'
      });
      return;
    }
    
    // 确保ID是字符串类型
    var applicationId = String(id);
    console.log('准备跳转，申请ID:', applicationId);
    
    // 使用最简单的跳转方式
    const targetUrl = `/pages/user/progress/detail/index?id=${applicationId}`;
    console.log('准备跳转到:', targetUrl);
    
    // 先显示加载提示
    setTimeout(() => {
            this.hideGlobalLoading();
      wx.navigateTo({ 
        url: targetUrl,
        success: function(res) {
          console.log('页面跳转成功:', res);
        },
        fail: function(err) {
          console.error('页面跳转失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    }, 300);
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    var that = this;
    that.setData({
      currentPage: 1,
      hasMore: true
    });
    that.loadApplications();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom: function() {
    if (this.data.loading || !this.data.hasMore) {
      return;
    }
    
    this.setData({
      currentPage: this.data.currentPage + 1
    });
    this.loadApplications();
  },

  // 返回按钮处理
  onBack: function() {
    // 如果是从申请页面跳转过来的，直接跳转到首页
    if (this.data.fromApplyPage) {
      wx.switchTab({
        url: '/pages/common/index/index'
      });
    } else {
      // 否则返回到上一页
      wx.navigateBack();
    }
  }
})